Passed
Pull Request — master (#163)
by Alejandro
06:15
created

SearchField.render   A

Complexity

Conditions 1

Size

Total Lines 23
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 23
ccs 0
cts 4
cp 0
rs 9.376
c 0
b 0
f 0
cc 1
crap 2
1
import React from 'react';
2
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
3
import { faSearch as searchIcon } from '@fortawesome/free-solid-svg-icons';
4
import PropTypes from 'prop-types';
5
import classnames from 'classnames';
6
import './SearchField.scss';
7
8 2
const DEFAULT_SEARCH_INTERVAL = 500;
9
10
export default class SearchField extends React.Component {
11 2
  static propTypes = {
12
    onChange: PropTypes.func.isRequired,
13
    className: PropTypes.string,
14
    placeholder: PropTypes.string,
15
  };
16 2
  static defaultProps = {
17
    className: '',
18
    placeholder: 'Search...',
19
  };
20
21
  state = { showClearBtn: false, searchTerm: '' };
22
  timer = null;
23
24
  searchTermChanged(searchTerm, timeout = DEFAULT_SEARCH_INTERVAL) {
25
    this.setState({
26
      showClearBtn: searchTerm !== '',
27
      searchTerm,
28
    });
29
30
    const resetTimer = () => {
31
      clearTimeout(this.timer);
32
      this.timer = null;
33
    };
34
35
    resetTimer();
36
37
    this.timer = setTimeout(() => {
38
      this.props.onChange(searchTerm);
39
      resetTimer();
40
    }, timeout);
41
  }
42
43
  render() {
44
    const { className, placeholder } = this.props;
45
46
    return (
47
      <div className={classnames('search-field', className)}>
48
        <input
49
          type="text"
50
          className="form-control form-control-lg search-field__input"
51
          placeholder={placeholder}
52
          value={this.state.searchTerm}
53
          onChange={(e) => this.searchTermChanged(e.target.value)}
54
        />
55
        <FontAwesomeIcon icon={searchIcon} className="search-field__icon" />
56
        <div
57
          className="close search-field__close"
58
          hidden={!this.state.showClearBtn}
59
          id="search-field__close"
60
          onClick={() => this.searchTermChanged('', 0)}
61
        >
62
          &times;
63
        </div>
64
      </div>
65
    );
66
  }
67
}
68